package com.kfm.base.thread.day02;

import java.util.concurrent.CountDownLatch;

public class Demo05 {

    public static void main(String[] args) {
        Operator operator = new Operator();
        // 线程计数
        CountDownLatch countDownLatch = new CountDownLatch(10);

        Runnable addRun = () ->{
            for (int i = 0; i < 1000; i++) {
                operator.add();
            }
            countDownLatch.countDown();
        };

        Runnable subRun = () -> {
            for (int i = 0; i < 1000; i++) {
                operator.sub();
            }
            countDownLatch.countDown();
        };


        for (int i = 0; i < 5; i++) {
            new Thread(addRun).start();
        }

        for (int i = 0; i < 5; i++) {
            new Thread(subRun).start();
        }


//        try {
//            Thread.sleep(5000);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }

        try {
            // 等待线程计数器为 0
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        System.out.println(operator.get());
    }
}


class Operator {

    private int i = 0;

    public void add(){
        synchronized (this){
            i ++;
        }
    }

    public void sub(){
        synchronized (this){
            i --;
        }
    }

    public int get(){
        return i;
    }
}
